package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.AccountInfoMapper;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.constant.GameTypeConstant;
import com.ruoyi.system.outto.core.region.SDZRegionalCovert;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.ISDZAPI;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.Buffer;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

import static com.ruoyi.system.outto.core.OutUrlConstant.SDZURL;

@Service
@Slf4j
public class SDZAPIImpl implements ISDZAPI {
    @Value("${desc.title}")
    private String descTitle;
    @Autowired
    private CommonApi commonApi;
    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private AccountInfoMapper accountInfoMapper;
    @Override
    public AjaxResult editGame(AccountInfo accountInfo, Long userId, SalePartner sa) {
        String sdzId = accountInfo.getSdzId();
        if (Objects.isNull(sdzId)){
            return AjaxResult.error("闪电猪未查到");
        }
        String des = accountInfo.getDes();
        Long id = accountInfo.getId();
        String title = "【"+descTitle + "_" + id + "】  "+ accountInfo.getLevel() + "  " + des;
        String gameType = accountInfo.getType();
        String sdzGameId = SDZRegionalCovert.getSdzGameId(gameType);
        if (StringUtils.isEmpty(sdzGameId)){
            return AjaxResult.error("闪电猪游戏类型未查到");
        }
        //图片
        StringBuilder imagesSb = new StringBuilder();
        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        if (CollectionUtils.isEmpty(infoImgs)) {
        } else {
            for (InfoImg img : infoImgs) {
                imagesSb.append(img.getImgUrl()).append(",");
            }
        }
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("guid",sdzId)
                .addFormDataPart("price",String.valueOf(accountInfo.getPrice()))
                .addFormDataPart("goods_title",title.length()>100?title.substring(0,99):title)
                .addFormDataPart("goods_describe",des.length()>500?des.substring(0,499):des)
                .addFormDataPart("thumb_image", StringUtils.isNotEmpty(accountInfo.getTitleImg())?accountInfo.getTitleImg():"https://game.ikbh.top/logo/no_img.jpg")
                .addFormDataPart("goods_number", String.valueOf(id))
                .addFormDataPart("server_name", accountInfo.getType())
                .addFormDataPart("goods_images", imagesSb.toString())
                .addFormDataPart("platform_name", String.valueOf(accountInfo.getRegional()))
                .build();

        Request request = getRequest(sa, body,"/editGoods");
        try {
            Buffer buffer = new Buffer();
            log.info(request.headers().toString());
            request.body().writeTo(buffer);
            //编码设为UTF-8
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = body.contentType();
            if (contentType != null) {
                charset = contentType.charset(Charset.forName("UTF-8"));
            }
//拿到request
            String requestString = buffer.readString(charset);
            log.info("闪电猪编辑请求参数:{}",requestString);
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            if (StringUtils.isEmpty(string)){
                log.info("闪电猪编辑失败:{}",response.toString());
            }
            Map<String, Object> result = new HashMap<>();
            log.info("闪电猪修改返回参数:{}",string);
            JSONObject jsonObject = JSONObject.parseObject(string);
            if (!"200".equals(jsonObject.getString("code"))) {
                result.put("code",500);
            }else {
                result.put("code",200);
            }
            result.put("req", request.body().toString());
            result.put("res",string);
            result.put("msg",jsonObject.get("msg"));
            return AjaxResult.success(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public AjaxResult addGame(AccountInfo accountInfo, Long userId ,SalePartner sa) {

        String des = accountInfo.getDes();
        Long id = accountInfo.getId();
        String title = "【"+descTitle + "_" + id + "】  "+ accountInfo.getLevel() + "  " + des;
        String gameType = accountInfo.getType();
        String sdzGameId = SDZRegionalCovert.getSdzGameId(gameType);
        if (StringUtils.isEmpty(sdzGameId)){
            return AjaxResult.error("闪电猪游戏类型未查到");
        }
        //图片
        StringBuilder imagesSb = new StringBuilder();
        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        if (CollectionUtils.isEmpty(infoImgs)) {
        } else {
            for (InfoImg img : infoImgs) {
                imagesSb.append(img.getImgUrl()).append(",");
            }
        }
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("price",String.valueOf(accountInfo.getPrice()))
                .addFormDataPart("category_id",sdzGameId)
                .addFormDataPart("goods_title",title.length()>100?title.substring(0,99):title)
                .addFormDataPart("goods_describe",des.length()>500?des.substring(0,499):des)
                .addFormDataPart("thumb_image", StringUtils.isNotEmpty(accountInfo.getTitleImg())?accountInfo.getTitleImg():"https://game.ikbh.top/logo/no_img.jpg")
                .addFormDataPart("goods_number", String.valueOf(id))
                .addFormDataPart("server_name", accountInfo.getType())
                .addFormDataPart("goods_images", imagesSb.toString())
                .addFormDataPart("platform_name", String.valueOf(accountInfo.getRegional()))
                .build();
        Request request = getRequest(sa, body,"/addGoods");
        try {
            Buffer buffer = new Buffer();
            log.info(request.headers().toString());
            request.body().writeTo(buffer);
            //编码设为UTF-8
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = body.contentType();
            if (contentType != null) {
                charset = contentType.charset(Charset.forName("UTF-8"));
            }
//拿到request
            String requestString = buffer.readString(charset);
            log.info("闪电猪请求参数:{}",requestString);
            Map<String, Object> result = new HashMap<>();
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            if (StringUtils.isEmpty(string)){
                log.info("闪电猪新增失败:{}",response.toString());
            }
            log.info("闪电猪新增返回参数:{}",string);
            JSONObject jsonObject = JSONObject.parseObject(string);
            if ("200".equals(jsonObject.getString("code"))) {
                result.put("code",200);
                String data = jsonObject.get("data").toString();
                accountInfo.setSdzId(data);
                accountInfo.setPrice(null);
                accountInfo.setNewPrice(null);

                AccountInfo upacc = new AccountInfo();
                upacc.setSdzId(data);
                upacc.setUpdateTime(new Date());
                upacc.setId(accountInfo.getId());

                accountInfoMapper.updateAccountInfo(upacc);

            }else {
                result.put("code",500);
            }
            result.put("req", request.body().toString());
            result.put("res",string);
            result.put("msg",jsonObject.get("msg"));

            return AjaxResult.success(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public AjaxResult delGame(AccountInfo accountInfo, Long userId ,SalePartner sa) {
        String sdzId = accountInfo.getSdzId();
        if (Objects.isNull(sdzId)){
            return AjaxResult.error("闪电猪未查到");
        }
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("guid",sdzId)
                .build();
        Request request = getRequest(sa, body,"/offShelfGoods");
        try {
            Map<String, Object> result = new HashMap<>();
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info("闪电猪下架请求参数:{}",request.body().toString());
            log.info("闪电猪下架返回参数:{}",string);
            JSONObject jsonObject = JSONObject.parseObject(string);
            if (!"200".equals(jsonObject.getString("code"))) {
                result.put("code",500);
            }else {
                result.put("code",200);
            }
            result.put("req", request.body().toString());
            result.put("res",string);
            result.put("msg",jsonObject.get("msg"));
            return AjaxResult.success(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Request getRequest(SalePartner sa, RequestBody body,String url) {
        String appId = sa.getSaleKey();
        String nonce = UUID.fastUUID().toString();
        String timestamp = new Date().getTime()/1000+"";
        String appKey = sa.getOther();
        String sign = DigestUtils.md5Hex(appId + appKey + timestamp + nonce).toUpperCase();
        return new Request.Builder()
                .url(SDZURL+url)
                .method("POST", body)
                .addHeader("x-sz-token", appId)
                .addHeader("x-sz-nonce", nonce)
                .addHeader("x-sz-signature", sign)
                .addHeader("x-sz-timestamp", timestamp)
                .addHeader("User-Agent", "apifox/1.0.0 (https://www.apifox.cn)")
                .build();
    }

    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("category_id",SDZRegionalCovert.getSdzGameId(GameTypeConstant.LOL))
                .build();
        String appId = "2021041632744106";
        String nonce = UUID.fastUUID().toString();
        String timestamp = new Date().getTime()/1000+"";
        String appKey = "9de3cd6591711c07ae46f039f53618e4";
        log.info(nonce);
        log.info(timestamp);
        String sign = DigestUtils.md5Hex(appId + appKey + timestamp + nonce).toUpperCase();
        Request request = new Request.Builder()
                .url("https://test.shanzhuyou.com:4433/regionalService")
                .method("POST", body)
                .addHeader("x-sz-token", appId)
                .addHeader("x-sz-nonce", nonce)
                .addHeader("x-sz-signature", sign)
                .addHeader("x-sz-timestamp", timestamp)
                .addHeader("User-Agent", "apifox/1.0.0 (https://www.apifox.cn)")
                .build();
        try {
            Response response = client.newCall(request).execute();
            log.info(String.valueOf(response));
            log.info(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
//        OkHttpClient client = new OkHttpClient().newBuilder()
//                .build();
//        MediaType mediaType = MediaType.parse("text/plain");
//        RequestBody body = RequestBody.create(mediaType, "");
//                String appId = "2021041632744106";
//        String nonce = UUID.fastUUID().toString();
//        String timestamp = new Date().getTime()/1000+"";
//        String appKey = "9de3cd6591711c07ae46f039f53618e4";
//        log.info(nonce);
//        log.info(timestamp);
//                String sign = DigestUtils.md5Hex(appId + appKey + timestamp + nonce).toUpperCase();
//                log.info(sign);
//
//        Request request = new Request.Builder()
//                .url("https://test.shanzhuyou.com:4433/getCategory")
//                .method("POST", body)
//                .addHeader("x-sz-token", appId)
//                .addHeader("x-sz-nonce", nonce)
//                .addHeader("x-sz-signature", sign)
//                .addHeader("x-sz-timestamp", timestamp)
//                .addHeader("User-Agent", "apifox/1.0.0 (https://www.apifox.cn)")
//                .build();
//        try {
//            Response response = client.newCall(request).execute();
//                       log.info(String.valueOf(response));
//            ResponseBody body1 = response.body();
//            log.info(body1.string());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
}
